﻿using MediatR;
using SmartCity.ProcessEngine.API.Write.Application.Commands.FormType;
using SmartCity.ProcessEngine.Domain;
using SmartCity.ProcessEngine.Errorcode;
using SmartCity.ProcessEngine.Infrastructure.Interfaces;

namespace SmartCity.ProcessEngine.API.Write.Application.CommandHandlers.FormType
{
    public class FormTypeAddCommandHandler:IRequestHandler<FormTypeAddCommand,ApiResult<int>>
    {
        private readonly IBaseRepository<WF_FromType> formTypeRep;

        public FormTypeAddCommandHandler(IBaseRepository<WF_FromType> formTypeRep)
        {
            this.formTypeRep = formTypeRep;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回添加任务</returns>
        public async Task<ApiResult<int>> Handle(FormTypeAddCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.code = ApiEnum.AddSuccess;
            result.message = ApiEnum.AddSuccess.ToString();

            int num = 1;
            //查询表中编号的最大值
            //var temp = formTypeRep.GetAll().OrderByDescending(x=>x.TypeNo).FirstOrDefault();
            //if(temp != null)
            //{
            //    num = Convert.ToInt32(temp.TypeNo.Replace("T", ""))+1;
            //}

            var temp = formTypeRep.GetAll().Max(x=>x.TypeNo);
            if(!string.IsNullOrEmpty(temp))
            {
                num = Convert.ToInt32(temp.Replace("T",""))+1 ;
            }

            WF_FromType enetity = new WF_FromType();
            enetity.TypeNo = "T" + num.ToString().PadLeft(3,'0');
            enetity.IndustryId = request.IndustryId;
            enetity.TypeName = request.TypeName;
            await formTypeRep.AddAsync(enetity);

            return await Task.FromResult(result);
        }
    }
}
